<template>
  <!-- 工程品质专项治理检查排名 -->
  <a-spin :spinning="loading">
    <a-card>
      <title-name :title="`${$route.query.month}月工程品质专项治理检查排名`"></title-name>
      <!-- 汇总排名信息 -->
      <!-- <Empty v-if="!Object.keys(detailsMap) || !Object.keys(detailsMap).length" description="暂无数据" /> -->
      <div style="padding: 0 20px 20px;" v-if="!isShowEdit">
        <div v-if="Object.keys(detailsMap).length > 0">
          <div v-for="(item, index) in detailsMap" :key="index" class="mb20">
            <title-name :title="index"></title-name>
            <div v-for="(i, idx) in item" :key="idx">
              <div class="branchName">{{ idx }}</div>
              <a-table bordered rowKey="id" :pagination="false" :columns="columns2" :dataSource="i"> </a-table>
            </div>
            <Empty v-if="!Object.keys(item) || !Object.keys(item).length" description="暂无数据" />
          </div>
        </div>
        <div v-else>
          <title-name :title="queryParam.nodeName" v-if="queryParam.type.indexOf('.') >= 0"></title-name>
          <Empty description="暂无数据" />
        </div>
      </div>
      <div style="padding: 0 20px 20px;" v-else>
        <title-name :title="key1"></title-name>
        <a-button v-if="isShowEdit" type="primary" @click="handleAdd({})">{{ key1 + '评分' }}</a-button>
        <div class="branchName">{{ key2 }}</div>
        <a-table bordered :rowKey="(record, index) => index" :pagination="false" :columns="columns2" :dataSource="dataSource"> </a-table>
      </div>
    </a-card>
    <!-- 编辑备注 -->
    <DialogForm ref="dialogForm" :is-emit="false" :visible.sync="visible" edit-model="E" :headerTitle="(form.id != '' ? '编辑' : '添加') + key1 + '评分'" :width="1000" :form="form" :formList="formList" :rules="rules" @confirm="submitCache" />
  </a-spin>
</template>

<script>
import { getSpecialScore, updateOrAddSpecialScore } from '@/api/quality/qualityMonth' // api
import { Empty } from 'ant-design-vue' // 无数据提示
import DialogForm from '@/components/DialogForm' // 表单弹窗
import SelectProject from '@/components/Select/SelectProject' // 分公司
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    fixed: 'left',
    align: 'center',
    customRender() {
      return arguments[1].branchComName !== '平均值' ? arguments[2] + 1 : ''
    }
  },
  {
    title: '分公司名称',
    // width: 120,
    // fixed: 'left',
    dataIndex: 'branchComName'
  },
  {
    title: '平均值',
    dataIndex: '-1',
    width: 80,
    align: 'center',
    fixed: 'right',
    customRender(e) {
      return e ?? '-'
    }
  }
]

export default {
  name: 'SpecialTreatment',
  components: {
    Empty,
    DialogForm
  },
  props: {
    // 请求参数
    queryParam: {
      type: Object,
      default: () => null
    }
  },
  computed: {
    columns2() {
      let columns = [
        {
          title: '序号',
          width: 80,
          align: 'center',
          dataIndex: 'index',
          customRender() {
            return arguments[1].projectName !== '平均值' ? arguments[2] + 1 : ''
          }
        },
        {
          title: '项目名称',
          width: 230,
          dataIndex: 'projectName'
        },
        {
          title: '考核得分',
          width: 160,
          dataIndex: 'value'
        },
        {
          title: '存在的问题',
          ellipsis: true,
          dataIndex: 'remarks'
        }
      ]
      // 节点若为分公司则添加操作按钮
      this.isShowEdit &&
        columns.push({
          title: '操作',
          dataIndex: 'actions',
          width: '180px',
          align: 'center',
          customRender: (text, record, index) => {
            return (<div>
                <a
                  onClick={() => this.handleAdd(record, index)}
                >
                  编辑
                </a>
                {
                !!!record.id && 
                  <a
                    class="ml20"
                    style="color: red"
                    onClick={() => this.handleDelete(index)}
                  >
                    删除
                  </a>
                }
                
              </div>)
          }
        })
      return columns
    },
    formList() {
      return [
        { 
          type: SelectProject, 
          attrs: {
            isSelf: false,
            branchComIds: [this.queryParam.branchComId],
            keyValue: 'branchComId',
            form: this.form,
            isClear: false,
          },
          disabled: this.form.id !== '',
          keyName: 'projectId', 
          label: '项目名称', 
          span: 12,
          selectChange: (e) => {
            if (e) {
              this.$refs.dialogForm.forms.projectName = e.name
            }
          }
        },
        { 
          type: 'BaseInputNumber', 
          keyName: 'value', 
          label: '考核得分',
          span: 12,
          attrs: {
            precision: 2,
            step: 0.01,
            min: 0,
            formatter: (value) => {
              return `${value}`.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
            }
          }
        },
        { 
          type: 'BaseTextarea',
          attrs: {
            maxLength: 10000,
            showLimitTip: false
          }, 
          keyName: 'remarks', 
          label: '存在的问题', 
          span: 24 
        },
      ] // 弹窗表单配置项
    },
  },
  data() {
    this.columns = columns
    return {
      loading: false, // 加载控件
      isShowEdit: false,
      form: {
        branchComId: this.queryParam.branchComId,
        id: '',
        remarks: '',
        projectId: '',
        projectName: '',
        value: void 0,
      }, // 编辑表单
      visible: false, // 弹窗显隐控件
      rules: {
        remarks: [{ required: true, whitespace: true, message: '请输入存在的问题', trigger: 'change' }],
        value: [{ required: true, message: '请输入考核得分', trigger: 'change' }],
        projectId: [{ required: true, whitespace: true, message: '请选择项目名称', trigger: 'change' }],
      }, // 校验规则
      detailsMap: {}, // 表格列表
      dataSource: [],
      key1: '',
      key2: '',
    }
  },
  mounted() {
    this.isShowEdit = this.queryParam.branchComId && (this.$route.query.editModel == 2 || this.$route.query.editModel == 4)
    // 初始化列表
    this.init()
  },
  methods: {
    /**
     * 初始化
     */
    init() {
      this.loading = true
      if (this.isShowEdit) {
        this.key1 = this.queryParam.parentName
        this.key2 = this.queryParam.nodeName
      }
      getSpecialScore(this.queryParam)
        .then((res) => {
          if (res.data) {
            // 映射列表表格信息
            const detailList = res.data.detailList || {}
            if (this.isShowEdit) {
              if (detailList[this.key1] && detailList[this.key1][this.key2] && detailList[this.key1][this.key2].length > 0) {
                this.dataSource =  detailList[this.key1][this.key2].map(item => {
                  if (!!item.value) {
                    item.value = Number((item.value)).toFixed(2)
                  }
                  item.qualityMonthId = this.$route.query.id
                  item.isAdjust = this.$route.query.isAdjust
                  item.branchComId = this.queryParam.branchComId
                  item.branchComName = this.key2
                  item.cateName = this.key1
                  item.yearMonth = this.queryParam.monthTime
                  item.type = this.queryParam.type
                  return item
                }).filter(item => item.projectName !== '平均值')
              } else {
                this.dataSource = []
              }
            }
            this.detailsMap = detailList
            // 映射统计表格信息
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleAdd(record, index) {
      this.form.remarks = record.remarks || ''
      this.form.id = record.id || ''
      this.form.value = record.value || void 0
      this.form.projectName = record.projectName || ''
      this.form.projectId = record.projectId || ''
      this.form.index = record.projectId ? index : this.dataSource.length
      this.form.isEdit = record.projectId ? true : false
      this.visible = true
    },
    handleDelete(i) {
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: '确认删除？',
        okText: '确认',
        cancelText: '关闭',
        onOk: () => {
          this.dataSource.splice(i, 1)
        }
      })
    },
    submitCache(form) {
      if (this.dataSource.filter((item, index) => item.projectId === form.projectId && form.index !== index).length > 0) {
        this.$message.warning(form.projectName + '项目已存在！')
        return false
      }
      if (!!form.value) {
        form.value = Number(form.value).toFixed(2)
      }
      form.qualityMonthId = this.$route.query.id
      form.isAdjust = this.$route.query.isAdjust
      form.branchComId = this.queryParam.branchComId
      form.branchComName = this.key2
      form.cateName = this.key1
      form.yearMonth = this.queryParam.monthTime
      form.type = this.queryParam.type
      if (form.isEdit) {
        const index = this.dataSource.findIndex(item => item.id === form.id)
        this.dataSource[index] = form
      } else {
        this.dataSource.push(form)
      }
      this.$message.success(form.isEdit ? '编辑成功！' : '添加成功！')
      this.$refs.dialogForm.loading = false
      this.visible = false
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      if (this.dataSource.length === 0) {
        this.$message.warning(this.key1 + '评分不能为空！')
        return false
      }
      this.$emit('submitLoading', true)
      updateOrAddSpecialScore(this.dataSource)
        .then((res) => {
          if (res.code === '0') {
            this.init()
            this.$message.success('提交成功！')
          }
        }).finally(() => {
          this.$emit('submitLoading', false)
        })
    }
  }
}
</script>

<style scoped>
.branchName {
  padding: 6px 0;
  text-align: center;
  font-weight: bolder;
}
</style>
